<?php
namespace modules\user;

use Exception;
use mytp\Model;
use modules\user\model\User as UserModel;
use mytp\Request;

class User extends Model{
  protected $user;
  protected $request;
  
  public function __construct(UserModel $user, Request $request) {
    $this->user = $user;
    $this->request = $request;
  }

  public function data() {
    return $this->user->get();
  }

  public function testPost() {
    // return $request->post('name');
    return $this->request->post();
  }

  public function testGet() {
    return $this->request->get();
  }

  // 接收表单数据
  public function save() {
    if($this->request->hasFile('image')) {
      $data['image'] = $this->uploadImage();
    }
  }

  public function uploadImage() {
    try {
      $file = $this->request->file('image');
      $allow_ext = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
      $ext = $file->extension();
      if(!in_array(strtolower($ext), $allow_ext)) {
        throw new Exception('文件上传失败: 文件拓展名应为: ' . implode(', ', $allow_ext));
      }
      // 根据当前日期生成对应文件夹
      $sub = date('Y-m/d');
      $name = $file->move('./uploads/image/' . $sub);
      return $sub . '/' . $name;
    } catch(Exception $err) {
      throw new Exception('文件上传失败: ' . $err->getMessage());
    }
  }

  public function success($res) {
    return $this->user->where('user_name', $res['name'])->where('user_pwd', $res['pwd'])->get();
  }
}
?>